﻿/*
 * Author: Duncan Jenkins / Martijn Koopman
 * 
 * Description: Turns a image into grayscale
 * */

using System.Drawing;
using System.Drawing.Imaging;

namespace LibraryCS {
    public class Grayscale : VisionAlgorithm {
        public Grayscale(string name) : base(name) { }
        public override Bitmap DoAlgorithm(Bitmap sourceImage) {
            // Create a new Bitmap to edit
            Bitmap image = new Bitmap(sourceImage.Width, sourceImage.Height);
            Rectangle rect = new Rectangle(0, 0, sourceImage.Width, sourceImage.Height);
            // Lock both bitmaps in memory
            BitmapData source = sourceImage.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
            BitmapData destination = image.LockBits(rect, ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);

            unsafe {
                int* sourcePtr = (int*)source.Scan0;
                int* destPtr = (int*)destination.Scan0;

                for (int i = 0; i < (source.Stride * source.Height) / 4; i++) {
                    // Extract current R, G and B values
                    byte a = (byte)(sourcePtr[i] >> 24);
                    byte r = (byte)(sourcePtr[i] >> 16);
                    byte g = (byte)(sourcePtr[i] >> 8);
                    byte b = (byte)sourcePtr[i];

                    // Calculate new R, G and B values and insert them into the new Bitmap
                    //r = (byte)((double)r * 0.21);
                    //g = (byte)((double)g * 0.71);
                    //b = (byte)((double)b * 0.07);

                    int value = (r + g + b) / 3;

                    destPtr[i] = a << 24 | (byte)value << 16 | (byte)value << 8 | (byte)value;
                }
            }

            sourceImage.UnlockBits(source);
            image.UnlockBits(destination);

            return image;
        }
    }
}
